package com.xuecheng.base.model;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import lombok.Data;
import lombok.ToString;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Mr.M
 * @version 1.0
 * @description 分页查询结果模型类
 * @date 2023/2/11 15:40
 */
@Data
@ToString
public class PageResult<T> implements Serializable {

    // 数据列表(数据)
    private List<T> items;

    //总记录数(总条数)
    private long counts;

    //当前页码
    private long pages;

    //每页记录数
    private long pageSize;



    public static<PO,VO> PageResult<VO> of(Page<PO> p, Class clazz){
        PageResult<VO> dto = new PageResult<>();

        dto.setPageSize(p.getSize());
        dto.setPages(p.getPages());
        dto.setCounts(p.getTotal());

        //当前页数据
        List<PO> records = p.getRecords();
        if (CollUtil.isEmpty(records)){
            //为空的话，返回一个空集合
            dto.setItems(Collections.emptyList());
            return dto;
        }

        List<VO> vos = BeanUtil.copyToList(records,clazz);
        dto.setItems(vos);

        return dto;

    }

    public static <PO,VO> PageResult<VO> of(Page<PO> p, Function<PO,VO> convertor) {
        PageResult<VO> dto = new PageResult<>();

        dto.setPageSize(p.getSize());
        dto.setPages(p.getPages());

        List<PO> records = p.getRecords();
        //做非空判断的原因是因为beanUtil空集合会报错
        if (CollUtil.isEmpty(records)) {

            dto.setItems(Collections.emptyList());
            return dto;
        }


        dto.setItems(records.stream().map(convertor).collect(Collectors.toList()));

        return dto;
    }
}
